import json

from django.http import JsonResponse
from django.shortcuts import render

# Create your views here
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU
from apps.users.views import LoginRequiredJsonMixin


class AddCarts(LoginRequiredJsonMixin,View):
    def post(self, request):
        # 1.接收数据
        data = json.loads(request.body.decode())
        sku_id = data.get('sku_id')
        count = data.get('count')
        # 2.验证数据

        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '查无此商品'})

        # 类型强制转换
        try:
            count = int(count)
        except Exception:
            count = 1
        # 3.判断用户的登录状态
        # request.user 如果是登录用户，就是 关联User的模型数据
        # is_authenticated = True 认证用户
        # 如果不是登录用户，就是匿名用户
        # 匿名用户的 is_authenticated = False
        #
        user = request.user
        redis_cli = get_redis_connection('carts')
        pipeline=redis_cli.pipeline()
        pipeline.hset('carts_%s'%user.id,sku_id,count)
        pipeline.sadd('selected_%s' % user.id, sku_id)
        pipeline.execute()
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
    def get(self,request):
        # 1.判断用户是否登录
        user=request.user
        if user.is_authenticated:

            # 2.登录用户查询redis
            #     2.1 连接redis
            redis_cli=get_redis_connection('carts')
            #     2.2 hash        {2:count,3:count,...}
            sku_id_counts=redis_cli.hgetall('carts_%s'%user.id)
            #     2.3 set         {2}
            selected_ids=redis_cli.smembers('selected_%s'%user.id)
            #     2.4 将 redis的数据转换为 和 cookie一样
            #    这样就可以在后续操作的时候 统一操作
            # {sku_id:{count:xxx,selected:xxx}}
            carts={}

            for sku_id,count in sku_id_counts.items():
                carts[int(sku_id)]={
                    'count':int(count),
                    'selected': sku_id in selected_ids
                }


        #{sku_id: {count: xxx, selected: xxx}}
        # 4 根据商品id查询商品信息
        # 可以直接遍历 carts
        # 也可以获取 字典的最外层的key，最外层的所有key就是商品id
            sku_ids=carts.keys()
        # [1,2,3,4,5]
        # 可以遍历查询
        # 也可以用 in
            skus=SKU.objects.filter(id__in=sku_ids)

            sku_list=[]
            for sku in skus:

                sku_list.append({
                'id':sku.id,
                'price':sku.price,
                'name':sku.name,
                'default_image_url':sku.default_image.url,
                'selected': carts[sku.id]['selected'],          #选中状态
                'count': int(carts[sku.id]['count']),                # 数量 强制转换一下
                'amount': sku.price*carts[sku.id]['count']      #总价格
            })
        # 6 返回响应
            return JsonResponse({'code':0,'errmsg':'ok','cart_skus':sku_list})

    def put(self, request):
            # 1.获取用户信息
            user = request.user
            # 2.接收数据
            data = json.loads(request.body.decode())
            sku_id = data.get('sku_id')
            count = data.get('count')
            selected = data.get('selected')
            # 3.验证数据
            if not all([sku_id, count]):
                return JsonResponse({'code': 400, 'errmsg': '参数不全'})

            try:
                SKU.objects.get(id=sku_id)
            except SKU.DoesNotExist:
                return JsonResponse({'code': 400, 'errmsg': '没有此商品'})

            try:
                count = int(count)
            except Exception:
                count = 1

            if user.is_authenticated:
                # 4.登录用户更新redis
                #     4.1 连接redis
                redis_cli = get_redis_connection('carts')
                #     4.2 hash
                redis_cli.hset('carts_%s' % user.id, sku_id, count)
                #     4.3 set
                if selected:
                    redis_cli.sadd('selected_%s' % user.id, sku_id)
                else:
                    redis_cli.srem('selected_%s' % user.id, sku_id)
                #     4.4 返回响应
                return JsonResponse({'code': 0, 'errmsg': 'ok', 'cart_sku': {'count': count, 'selected': selected}},safe=False)

class allCart(View):
    def put(self,request):
        user=request.user
        data = json.loads(request.body.decode())
        selected = data.get('selected')
        if user.is_authenticated:
            redis_cli = get_redis_connection('carts')
            if selected:
                redis_cli.sadd('selected_%s' % user.id,1,2)
            else:
                redis_cli.srem('selected_%s' % user.id,1,2)
            return JsonResponse({'code': 0, 'errmsg': 'ok'})